import subprocess
import jiesuan
from skimage import io
import os
import time
# 预设数据
a = [
    [0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0],
    [0,  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0],
    [0,  2, 0, 0, 0, 0, 0, 0, 0, 0, 9,  0],
    [0,  3, 0, 0, 0, 0, 0, 0, 0, 0, 8,  0],
    [0,  4, 0, 0, 0, 0, 0, 0, 0, 0, 7,  0],
    [0,  5, 0, 0, 0, 0, 0, 0, 0, 0, 6,  0],
    [0,  6, 0, 0, 0, 0, 0, 0, 0, 0, 5,  0],
    [0,  7, 0, 0, 0, 0, 0, 0, 0, 0, 4,  0],
    [0,  8, 0, 0, 0, 0, 0, 0, 0, 0, 3,  0],
    [0,  9, 0, 0, 0, 0, 0, 0, 0, 0, 2,  0],
    [0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,  0],
    [0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0]
]

x=[]
y=[]


def get_a():
    """获取截图out.png"""
    process = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)
    screenshou = process.stdout.read()
    screenshou = screenshou.replace(b'\r\n',b'\n')
    with open('out.png','wb') as f:
        f.write(screenshou)
    """保存截图文件out.png"""
    im = io.imread('out.png')
    """计算得到各个方块的位置，并存储到x，y"""
    for i in range(10):
        y.append(955 + 108 * i)
        x.append(55 + 108 * i)
    """x_0,y_0二位数组的横纵坐标"""
    x_0 = 1
    y_0 = 1
    for i in x:
        for j in y:
            p = im[j, i, 0]
            """
            1 蓝 60-70
            2 绿 120-130
            3 紫 220-230
            4 红 240-250
            5 黄 250-260
            6 其他 
            """
            if 60 < p < 70:
                a[x_0][y_0] = 1
            elif 120 < p < 130:
                a[x_0][y_0] = 2
            elif 220 < p < 230:
                a[x_0][y_0] = 3
            elif 240 < p < 250:
                a[x_0][y_0] = 4
            elif 250 < p < 260:
                a[x_0][y_0] = 5
            else:
                a[x_0][y_0] = 6
            if x_0 > 9:
                x_0 = 1
            else:
                x_0 += 1
        if y_0 > 9:
            y_0 = 1
        else:
            y_0 += 1


def dianji(x, y):
    """点击指定的像素"""
    y_1=str(x)
    x_1=str(y)
    print(x, y)
    """adb shell input swipe x x x x x为滑动点击，这里是为了防止点触点击时间太短而虚触"""
    dianjiyuju = 'adb shell input swipe '+x_1+' '+y_1+' '+x_1+' '+y_1+' '+'10'
    print(dianjiyuju)
    os.system(dianjiyuju)


if __name__ == '__main__':
    mode = input("请确定手机打开消灭星星大师并连接电脑，输入y继续。y/n")
    if mode == y:
        while True:
            get_a()
            c = jiesuan.jiesuan(a)
            dianji(int(955 + 108 * c/100), 55 + 108 * (c%100))
            """这里time.sleep是可以自定义两次计算的间隔时间"""
            time.sleep(0)
    else:
        print("请重新运行程序")


